import json
import random
import time
import logging
import os
import sys
import requests
import zipfile 

from playwright.sync_api import sync_playwright


# 读取配置文件
def load_config():
    with open('config.json', 'r', encoding='utf-8') as f:
        config = json.load(f)
    return config

# 获取浏览器路径
def get_resource_path(relative_path,chromium_url):
      # 在当前路径下查找浏览器
    base_path = os.path.abspath("./chrome-win/")
    browser_path = os.path.join(base_path, relative_path)

    # # 如果浏览器不存在，则下载并安装
    if not os.path.exists(browser_path):
        print(f"浏览器未找到，开始下载并安装...")
        install_chromium(chromium_url, "./")  # 下载并安装 Chromium
        browser_path = os.path.join(base_path, relative_path)  # 获取安装后的浏览器路径

    return browser_path

# # 下载并解压 Chromium
def install_chromium(chromium_url, install_dir):
    print("正在下载 Chromium...")
    response = requests.get(chromium_url, stream=True)
    zip_path = os.path.join(install_dir, "chromium.zip")
    
    # 下载压缩包
    with open(zip_path, 'wb') as f:
        for chunk in response.iter_content(chunk_size=128):
            f.write(chunk)

    # 解压缩
    print("解压 Chromium...")
    with zipfile.ZipFile(zip_path, 'r') as zip_ref:
        zip_ref.extractall(install_dir)

    # 删除下载的 zip 文件
    os.remove(zip_path)  # 删除压缩包
    print("Chromium 下载并安装完成!")

# 自动发送弹幕的函数
def send_barrage(page, barrage_text):
    try:
        # 定位到输入框和发送按钮，替换成实际的选择器
        input_box = page.locator("textarea.chat-input.border-box")  # 替换为实际输入框的 CSS 选择器
        send_button = page.locator("button.bl-button.live-skin-highlight-button-bg")  # 替换为实际发送按钮的 CSS 选择器
        
        input_box.fill(barrage_text)  # 输入弹幕
        send_button.click()  # 点击发送按钮
        print(f"弹幕发送成功: {barrage_text}")
    except Exception as e:
        print(f"发送失败: {e}")

# 自动发送弹幕
def auto_send_barrage(live_room_url, barrage_list, chromium_url):
    with sync_playwright() as p:
        # 启动浏览器
        chromium_path = get_resource_path('chrome.exe',chromium_url)  # 替换为正确路径
        browser = p.chromium.launch(executable_path=chromium_path,headless=False)  # headless=False 表示非无头模式，方便调试
        # chromium_path = p.chromium.executable_path
        # print(f"Chromium 浏览器路径: {chromium_path}")
        page = browser.new_page()

        # 访问直播页面
        page.goto(live_room_url)  # 使用从配置文件读取的 URL
        
        # 等待页面加载完成
        time.sleep(5)

        # 模拟发送弹幕
        while True:
            # 随机选择一条弹幕
            barrage_text = random.choice(barrage_list)

            # 发送弹幕
            send_barrage(page, barrage_text)

            # 设置一个随机的发送间隔，防止过于频繁
            time.sleep(random.uniform(2, 5))  # 随机时间间隔 2 到 5 秒

        # 关闭浏览器
        browser.close()


if not os.path.exists('./log'):
    os.makedirs('./log')
# 设置日志配置
logging.basicConfig(filename='./log/error_log.txt',  level=logging.ERROR, encoding='utf-8')

if __name__ == "__main__":
    # 加载配置文件
    config = load_config()
    #获取浏览器下载地址
    chromium_url = config.get('chromium_url')
    # 获取直播间地址和弹幕列表
    live_room_url = config.get('live_room_url')
    barrage_list = config.get('barrage_list')

    # 开始发送弹幕
    print("开始发送弹幕...")
    try:
        auto_send_barrage(live_room_url, barrage_list,chromium_url)
    except Exception as e:
        logging.error(f"发生错误: {e}")
        raise